<?php
/**
 * @copyright 
 * @license https://opensource.org/licenses/Apache-2.0
 * @link https://www.gougucms.com
 */
 
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\BaseController;
use app\admin\model\Order as OrderModel;
use app\admin\validate\OrderValidate;
use app\common\controller\WxPay;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\View;

class Order extends BaseController

{
	/**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new OrderModel();
		$this->uid = get_login_admin('id');
    }
    /**
    * 数据列表
    */
    public function datalist()
    {
        if (request()->isAjax()) {
			$param = get_params();
			$where = [];
			$where[] = ["delete_time","=",0];
			$where[] = ["status",">",0];
            if (!empty($param['nickname'])) {
                $uids = Db::name('user')->where([['nickname','like',"%{$param['nickname']}%"]])->column('id');
                $where[] = ['uid','in',$uids];
            }
            if (!empty($param['order_no'])) {
                $where[] = ['order_no','like',"%{$param['order_no']}%"];
            }
            if (!empty($param['imei'])) {
                $device = Db::name('device')->where(['imei'=>$param['imei']])->find();
                if (!empty($device)) {
                    $where[] = ["device_id","=",$device['id']];
                } else {
                    $where[] = ["device_id","=",0];
                }
            }
            if (!empty($param['pay_type'])) {
                $where[] = ['pay_type','=',$param['pay_type']];
            }
            if (!empty($param['status'])) {
                $where[] = ['status','=',$param['status']];
            }
            $list = $this->model->getOrderList($where,$param);
            return table_assign(0, '', $list);
        }
        else{
            return view();
        }
    }

    /**
    * 添加
    */
    public function add()
    {
        if (request()->isAjax()) {		
			$param = get_params();	
			
            // 检验完整性
            try {
                validate(OrderValidate::class)->check($param);
            } catch (ValidateException $e) {
                // 验证失败 输出错误信息
                return to_assign(1, $e->getError());
            }
			
            $this->model->addOrder($param);
        }else{
			return view();
		}
    }
	

    /**
    * 编辑
    */
    public function edit()
    {
		$param = get_params();
		
        if (request()->isAjax()) {			
            // 检验完整性
            try {
                validate(OrderValidate::class)->check($param);
            } catch (ValidateException $e) {
                // 验证失败 输出错误信息
                return to_assign(1, $e->getError());
            }
			
            $this->model->editOrder($param);
        }else{
			$id = isset($param['id']) ? $param['id'] : 0;
			$detail = $this->model->getOrderById($id);
			if (!empty($detail)) {
				View::assign('detail', $detail);
				return view();
			}
			else{
				throw new \think\exception\HttpException(404, '找不到页面');
			}			
		}
    }


    /**
    * 查看信息
    */
    public function read()
    {
        $param = get_params();
		$id = isset($param['id']) ? $param['id'] : 0;
		$detail = $this->model->getOrderById($id);
		if (!empty($detail)) {
            $device = Db::name('device')->where('id',$detail['device_id'])->find();
            $user = Db::name('user')->where('id',$detail['uid'])->find();
            $detail['user_info'] = $user['nickname'].'(ID：'.$detail['uid'].')';
            $detail['imei'] = $device['imei'];
            $address = json_decode($detail['address'],true);
            $detail['addr'] = $address['user_name'].'/'.$address['address'];
            if (!empty($detail['pay_time'])) {
                $detail['pay_time'] = datetime($detail['pay_time']);
            }
            if (!empty($detail['sh_img'])) {
                $detail['sh_img'] = explode(',',$detail['sh_img']);
            }
            if (!empty($detail['sh_time'])) {
                $detail['sh_time'] = datetime($detail['sh_time']);
            }
			View::assign('detail', $detail);
			return view();
		}
		else{
			throw new \think\exception\HttpException(404, '找不到页面');
		}
    }

    /**
     * 审核
     */
    public function examine()
    {
        $param = get_params();
        $data = Db::name('order')->where('id',$param['id'])->find();
        if (empty($data)) {
            return error('未找到该记录');
        }
        if ($data['status'] == 3) {
            return error('该订单已处理');
        }
        $save['update_time'] = time();
        if ($param['type'] == 1) {
            //通过
            $save['status'] = 3;
            $save['sh_status'] = 2;
            //原路退回账户
            if ($data['pay_type'] == 1) {
                $wx = new WxPay();
                $refund_notify_url = request()->domain()."/api/notify/backTeamPayResult";
                $back = [
                    'order_no' => $data['order_no'],
                    'out_found_no' => $data['out_found_no'],
                    'amount' => $data['amount']
                ];
                $wx->refund($back,$refund_notify_url);
            }
            if ($data['pay_type'] == 2) {
                Db::name('user')->where('id',$data['uid'])->inc('score',floatval($data['amount']))->update();
                Db::name('score_log')->insert([
                    'uid' => $data['uid'],
                    'title' => '订单退款',
                    'type' => 1,
                    'order_no' => $data['order_no'],
                    'num' => $data['amount'],
                    'create_time' => time(),
                ]);
            }
        } else {
            $save['status'] = 3;
            $save['sh_status'] = 3;
            $save['refuse'] = $param['refuse'];
        }
        Db::name('order')->where('id',$param['id'])->update($save);
        return success('操作成功');
    }

    /**
    * 删除
	* type=0,逻辑删除，默认
	* type=1,物理删除
    */
    public function del()
    {
        $param = get_params();
		$id = isset($param['id']) ? $param['id'] : 0;
		$type = isset($param['type']) ? $param['type'] : 0;

        $this->model->delOrderById($id,$type);
   }
}
